package com.wenx.thread;

import java.util.List;
import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 两个线程交替打印
 */
public class ThreadMain2 {

    static Thread thread1 = null;
    static Thread thread2 = null;


    public static void main(String[] args) {

        thread1 = new Thread(new Run1(), "线程1");
        thread2 = new Thread(new Run2(), "线程2");

        thread1.start();
        thread2.start();

        //TimeUnit.SECONDS.sleep(10L);

    }

    static class Run1 implements Runnable {

        @Override
        public void run() {
            List<Integer> collect = Stream.of(1, 2, 3, 4, 5, 6, 7, 8)
                    .collect(Collectors.toList());
                for (Integer integer : collect) {
                    System.out.print(integer + " ");
                    LockSupport.unpark(thread2);
                    //等待
                    LockSupport.park();
                }

        }
    }

    static class Run2 implements Runnable {

        @Override
        public void run() {
            List<String> collect = Stream.of("a", "b", "c", "d", "e", "f", "g", "h")
                    .collect(Collectors.toList());
                for (String str : collect) {
                    LockSupport.park();
                    System.out.print(str + " ");
                    LockSupport.unpark(thread1);
                }
        }
    }

}
